<?php

namespace App\Http\Controllers;

use App\Supports\ErrorTrait;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Controller as BaseController;

class Controller extends BaseController
{
    use AuthorizesRequests, ValidatesRequests, ErrorTrait;

    /**
     * 成功返回.
     *
     * @param array|Object $data
     * @param string $msg
     * @param int $code
     * @param array|false $header
     * @param int $time
     * @return JsonResponse
     */
    public function responseSuccess(array|object $data = [], string $msg = '', int $code = 0, bool $header = false, int $time = 300): JsonResponse
    {
        if (empty($msg)) {
            $msg = 'success';
        }
        $response = response()->json(['code' => $code, 'msg' => $msg, 'data' => $data]);
        if ($header) {
            $response->header('Cache-Control', "max-age={$time}");
            $response->header('Expires', gmdate('D, d M Y H:i:s \G\M\T', time() + $time));
        }

        return $response;
    }

    /**
     * 失败返回.
     *
     * @param array $data
     * @param string $msg
     * @param int $code
     * @return JsonResponse
     */
    public function responseError(array $data = [], string $msg = 'fail', int $code = 1): JsonResponse
    {
        return response()->json([
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ]);
    }

    /**
     * 自定义返回.
     *
     * @param array $data
     * @param string|null $msg
     * @param int|null $code
     * @return JsonResponse
     */
    public function customResponse(array $data = [], string $msg = null, int $code = null): JsonResponse
    {
        if ($msg === null) {
            $msg = 'custom msg';
        }

        if ($code === null) {
            $code = 1;
        }

        return response()->json([
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ]);
    }
}
